package com.dekun.workhard.config.security;

import com.alibaba.druid.util.StringUtils;
import com.dekun.workhard.entity.SysMenu;
import com.dekun.workhard.entity.SysUser;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * security userDetail
 */
@Data
public class CustomerUserDetail implements UserDetails {

    /**
     * 用户
     */
    private SysUser user;

    /**
     * 权限集合
     */
    private List<SysMenu> menus;



    public CustomerUserDetail(SysUser user, List<SysMenu> menus) {
        this.user = user;
        this.menus = menus;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(!CollectionUtils.isEmpty(menus)){
          return  menus.stream()
                  .filter(x->!StringUtils.isEmpty(x.getPerms()))
                  .map(x->new SimpleGrantedAuthority(x.getPerms()))
                  .collect(Collectors.toSet());
        }

        return null;
    }

    @Override
    public String getPassword() {
        if(Objects.nonNull(user)){
           return user.getPassword();
        }
        return null;
    }

    @Override
    public String getUsername() {
        if(Objects.nonNull(user)){
           return user.getLoginName();
        }
        return null;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
